/*
 * Created on Nov 4, 2011
 * pingAllIp.java V1.0
 *
 * Copyright Notice =========================================================
 * This file contains proprietary information of Huawei Technologies Co. Ltd.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2006 =======================================================
 */
package com.ping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;




public class PingAllIp extends Thread
{
    private int retry = 4;

    private int timeout = 300;
    
    private String targetIP;
    
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //任务数
    private static int taskNum = 255;
    //完成的任务数
    private static int finishNum = 0;
    
    private static Vector allowIPs = new Vector();
    
    private static String ipArea = "";
    
    public static void main(String[] args)
    {
        //格式 192.168.203.1-255
        ipArea = System.getProperty("ipArea");
        if(null == ipArea || ipArea.length()==0)
        {
            ipArea = "192.168.203.1-255";
        }
        
        String ipPrefix = ipArea.substring(0, ipArea.lastIndexOf(".")+1);
        String ipPostfix = ipArea.substring(ipArea.lastIndexOf(".")+1, ipArea.length());
        int startIndex = 1;
        int endIndex = 255;
        try
        {
            startIndex = Integer.parseInt(ipPostfix.split("-")[0]);
            endIndex = Integer.parseInt(ipPostfix.split("-")[1]);
        }
        catch (NumberFormatException e1)
        {
            System.out.println("您的输入格式不规范，请看之前的提示！");
            e1.printStackTrace();
            return;
        }
        taskNum = endIndex - startIndex + 1;
        
        if (args.length > 0 && args[0] != null)
        {
            taskNum = Integer.parseInt(args[0]);
            if (taskNum <= 0 || taskNum > 255)
            {
                System.out.println("您的输入格式不规范，请看之前的提示！");
                return;
            }
        }
        for (int i = startIndex; i <= endIndex; i++)
        {
            PingAllIp pingAllIp = new PingAllIp();
            pingAllIp.targetIP = ipPrefix + i;
            pingAllIp.start();
            if(taskNum>100)
            {
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException e)
                {
                }
            }
        }
    }
    
    private String ping()
    {
        String resultStr = "";
        // 结果对象
        PingResultPO result = new PingResultPO();
        result.setTargetIP(targetIP);
        result.setSent(this.retry);
        synchronized (sdf)
        {
            result.setPingTime(sdf.format(new Date()));
        }
        
        String cmd = "ping " + targetIP + " -w " + this.timeout + " -n "
                + this.retry;
        resultStr = executeByWindows(result, cmd);
        return resultStr;
    }
    
    public String executeByWindows(PingResultPO result, String cmd)
    {
        Process p = null;
        String resultStr = "";
        try
        {
            p = Runtime.getRuntime().exec(cmd);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            StringBuffer sb = new StringBuffer(cmd);
            String s = null;
            
          //最大连续丢包数
            int maxContinuousLost = 0;
            //连续丢包数
            int continuousLost = 0;
            while ((s = bufferedReader.readLine()) != null)
            {
                s = s.toLowerCase();
                if (s.indexOf("ping") > -1 || s.indexOf("approximate") > -1
                        || "".equals(s) || "\n".equals(s))
                {
                    continue;
                }
                
                if(s.indexOf("packets")>-1 || s.indexOf("数据包")>-1)
                {
                    String[] sArr = s.split(",");
                    if(sArr.length==1)
                        sArr = s.split("，");
                    result.setSent(Integer.parseInt(sArr[0].substring(sArr[0]
                            .indexOf("= ") + 2, sArr[0].length())));
                    
                    result.setReceived(Integer.parseInt(sArr[1].substring(
                            sArr[1].indexOf("= ") + 2, sArr[1].length())));
                    
                    result.setLost(Integer.parseInt(sArr[2].substring(sArr[2]
                            .indexOf("= ") + 2, sArr[2].indexOf("(") - 1)));
                    if(s.indexOf("100%")>0)
                    {
                        // System.out.println(this.targetIP + "可用");
                        allowIPs.add(this.targetIP);
                    }
                }
                else if(s.indexOf("minimum")>-1 || s.indexOf("最短")>-1)
                {
                    String[] sArr2 = s.split(",");
                    if(sArr2.length==1)
                        sArr2 = s.split("，");
                    result
                            .setMiniNum(Integer.parseInt(sArr2[0].substring(
                                    sArr2[0].indexOf("= ") + 2, sArr2[0]
                                            .length() - 2)));
                    result
                            .setMaxiNum(Integer.parseInt(sArr2[1].substring(
                                    sArr2[1].indexOf("= ") + 2, sArr2[1]
                                            .length() - 2)));
                    result
                            .setAverage(Integer.parseInt(sArr2[2].substring(
                                    sArr2[2].indexOf("= ") + 2, sArr2[2]
                                            .length() - 2)));
                    //sb.append("\nping  " + targetIP + "   " + s);
                }
              //是否连续丢包
                else if (s.indexOf("from") > -1 || s.indexOf("来自") > -1)
                {
                    continuousLost = 0;
                }
                else
                {
                    continuousLost++;
                }
                if (continuousLost > maxContinuousLost)
                {
                    maxContinuousLost = continuousLost;
                }
                sb.append("\n" + s);
                
            }
            //结束进程
            p.destroy();
            
            System.out.println(sb.toString());
            
            
        }
        catch (Exception e)
        {
            System.out.println("执行任务出现异常!");
            e.printStackTrace();
        }
        finally
        {
            if (p != null)
                p.destroy();
        }
        return resultStr;
    }

    public void run()
    {
        ping();
        finishNum ++;
        if(taskNum==finishNum)
        {
            System.out.println("-----------可用的ip地址列表(" + ipArea + ")-----------");
            Iterator i=allowIPs.iterator();
            for(;i.hasNext();)
            {
                System.out.println(i.next());
            }
        }
        
    }

}
